package com.garden.rocketmq.learn.demo.producer;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 异步生产者 发送异步消息
 * 用于注重消息发送时效性的场景，如推送通知
 * Created by Garden on 2020/7/22.
 */
public class AsyncProducer {

    public static void main(String[] args) throws MQClientException, UnsupportedEncodingException, RemotingException, InterruptedException, MQBrokerException {
        //实例化消息生产者Producer
        DefaultMQProducer producer = new DefaultMQProducer("async_producer_group");
        //设置NameServer的地址，Producer启动后通过NameServer获取目标Topic的路由信息
        producer.setNamesrvAddr("localhost:9876");
        //设置发送失败后消息重试发送次数，默认为2，可能会造成发送重复，由开发者根据使用场景自定义设置
        producer.setRetryTimesWhenSendFailed(0);
        //启动Producer实例
        producer.start();

        int messageCount = 100;
        // 根据消息数量实例化倒计时计算器，用于挂起主线程main-thread，等待监听broker响应线程都结束后再重新启动
        final CountDownLatch countDownLatch = new CountDownLatch(messageCount);
        //发送消息
        for (int i = 0; i < messageCount; i++) {
            final int index = i;
            //创建消息，指定主题Topic，标签Tag，业务标识Key，消息体MsgBody [Tag可用于消息过滤，Key可用于消息查询]
            Message msg = new Message("test_topic", "async_producer_tag", "async_producer_key." + i, ("AsyncProducer Msg." + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
            //声明SendCallback接收异步返回结果的回调方法[producer使用线程池处理回调方法onSuccess或onException]
            producer.send(msg, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.printf("%-10d OK %s %n", index,
                            sendResult.getMsgId());
                    countDownLatch.countDown();
                }
                @Override
                public void onException(Throwable e) {
                    System.out.printf("%-10d Exception %s %n", index, e);
                    e.printStackTrace();
                    countDownLatch.countDown();
                }
            });
        }
        //等待5s重新启动主线程main-thread
        countDownLatch.await(5, TimeUnit.SECONDS);
        //发送完毕，关闭Producer实例。
        producer.shutdown();
    }

}
